<script lang="ts" setup>
import { ref, computed, Ref, reactive, onMounted } from "vue";
import { Edit } from "@element-plus/icons-vue";
import Mediator from "@/types/response/mediator";
import { ElMessage } from "element-plus";
import {
  getAllMediators,
  addMediator,
  updateMediator,
  getAllOrganizations,
} from "@/axios/mediator/mediatorReq";
import { changeUserState, getUserStatesByIds } from "@/axios/admin/accountReq";
import MediatorsOrganization from "@/types/response/mediatorsOrganization";

interface ExtendedMediator extends Mediator {
  state?: number;
}
const gender = [
  {
    value: 1,
    label: "男",
  },
  {
    value: 0,
    label: "女",
  },
];
const orgConfig: {
  orgs: MediatorsOrganization[];
  init: Function;
} = reactive({
  orgs: [],
  init: () => {
    getAllOrganizations().then((res) => {
      orgConfig.orgs = res;
    });
  },
});
onMounted(() => {
  orgConfig.init();
});
const stateOptions = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "停用",
  },
];

const typeOptions = [
  {
    value: 1,
    label: "签约调解员",
  },
  {
    value: 2,
    label: "社会调解员",
  },
];
//用户搜索时输入的名字
const name = ref("");

const rulesFormRef = ref();

const workOrg = ref("");

const mediators: Ref<Mediator[]> = ref([]);

// 控制添加调解员弹窗
const dialogVisible = ref(false);

// 添加调解员数据模型
const mediatorModel = ref<ExtendedMediator>(new Mediator());

// 性别选择框绑定的值
const genderValue = ref<number>();

// 状态选择框绑定的值
const stateValue = ref<number>();

// 获取调解员列表
const getMediators = async () => {
  let result = await getAllMediators();
  mediators.value = result;
  let mIds = [];
  result.forEach((mediator) => {
    mIds.push(mediator.mId);
  });
  let states = await getUserStatesByIds(mIds);
  mediators.value = mediators.value.map((mediator) => ({
    ...mediator,
    state: states.get(mediator.mId) || undefined,
  }));
};
getMediators();

// 添加调解员表单校验
const rules = {
  name: [{ required: true, message: "请输入调解员姓名", trigger: "blur" }],
  birthday: [{ required: true, message: "请输入出生年月", trigger: "blur" }],
  idNum: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  workOrg: [{ required: true, message: "请输入工作单位", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  type: [
    { required: true, message: "请输入是否为专业调解员", trigger: "change" },
  ]
};
//添加调解员函数
const addMediators = () => {
  title.value = "新增调解员";
  dialogVisible.value = true;
  genderValue.value = 1;
  stateValue.value = 1;
  editIndex.value = null;
  rulesFormRef.value?.resetFields();
};
const editIndex = ref<number | null>(null);

const editMediator = (index: number, mediator: ExtendedMediator) => {
  title.value = "编辑调解员";
  mediatorModel.value=new Mediator();
  dialogVisible.value = true;
  mediatorModel.value = { ...mediator };
  genderValue.value = mediator.gender;
  stateValue.value = mediator.state;
  editIndex.value = index;
  rulesFormRef.value?.clearValidate();
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (genderValue.value) {
    mediatorModel.value.gender = genderValue.value;
  }
  if (stateValue.value) {
    mediatorModel.value.state = stateValue.value;
  }
  if (editIndex.value !== null) {
    //更新调解员信息
    const success = await updateMediator(mediatorModel.value);
    if (success) {
      mediators.value[editIndex.value] = { ...mediatorModel.value };
      editIndex.value = null;
      ElMessage({
        type: "success",
        message: "更新信息成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "更新信息失败",
      });
    }
  } else {
    //添加调解员信息
    const mediator = await addMediator(mediatorModel.value);
    if (mediator) {
      mediators.value.push(mediator);
      ElMessage({
        type: "success",
        message: "添加调解员成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "添加调解员失败",
      });
    }
  }
  // 这里可以添加保存到 mediators 数组的逻辑
  console.log("提交的调解员信息:", mediatorModel.value);
  dialogVisible.value = false;
};

// 切换调解员状态的方法
const toggleState = async (mediator: ExtendedMediator) => {
  mediator.state = mediator.state === 1 ? 0 : 1;
  const success = await changeUserState(mediator.mId, mediator.state);
  if (success) {
    mediator.state = mediator.state;
    ElMessage({
      type: "success",
      message: "状态切换成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "状态切换失败",
    });
  }
};

const title = ref("");

const filteredMediators = computed(() => {
  return mediators.value.filter(
    (mediator: ExtendedMediator) =>
      (!name.value || mediator.name.includes(name.value)) &&
      (!workOrg.value ||
        (mediator.workOrg && mediator.workOrg.includes(workOrg.value)))
  );
});

const table = ref(false);
const selectedMediator: Ref<Mediator> = ref(null);

const openDrawer = (respondent: any) => {
  selectedMediator.value = respondent;
  table.value = true;
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>调解员管理</span>
        <div class="extra">
          <el-button type="primary" @click="addMediators">新增调解员</el-button>
        </div>
      </div>
    </template>
    <!-- 搜素表单 -->
    <el-form inline>
      <el-form-item label="姓名：">
        <el-input
          v-model="name"
          style="width: 240px"
          clearable
          placeholder="请输入筛选姓名"
        />
      </el-form-item>
      <el-form-item label="工作单位：">
        <el-input
          v-model="workOrg"
          style="width: 240px"
          clearable
          placeholder="请输入工作单位"
        />
      </el-form-item>
    </el-form>

    <el-table :data="filteredMediators" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="联系方式" prop="phone"></el-table-column>
      <el-table-column label="工作单位" prop="workOrg"></el-table-column>
      <el-table-column label="状态" prop="state">
        <template #default="scope">
          {{ scope.row.state === 1 ? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            :disabled="scope.row.state === 0"
            @click="editMediator(scope.$index, scope.row)"
          ></el-button>
          <el-button
            :type="scope.row.state === 1 ? 'danger' : 'success'"
            circle
            plain
            @click="toggleState(scope.row)"
          >
            {{
              stateOptions.find((s) => s.value === scope.row.state)?.label ===
              "启用"
                ? "停用"
                : "启用"
            }}
          </el-button>
          <el-button text type="primary" @click="openDrawer(scope.row)"
            >详细</el-button
          >
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="mediatorModel"
        :rules="rules"
        label-width="140px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="调解员姓名" prop="name">
          <el-input
            v-model="mediatorModel.name"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="genderValue" placeholder="请选择性别">
            <el-option
              v-for="item in gender"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthDate">
          <el-date-picker
            v-model="mediatorModel.birthDate"
            type="date"
            placeholder="选择日期"
            format="YYYY年MM月"
            value-format="YYYY年MM月"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input
            v-model="mediatorModel.idNum"
            minlength="18"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="mediatorModel.phone"
            :disabled="editIndex !== null"
            minlength="11"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="mediatorModel.education">
            <el-option :label="'博士'" :value="'博士'"></el-option>
            <el-option :label="'研究生'" :value="'研究生'"></el-option>
            <el-option :label="'大学'" :value="'大学'"></el-option>
            <el-option :label="'高中'" :value="'高中'"></el-option>
            <el-option :label="'初中'" :value="'初中'"></el-option>
            <el-option :label="'大专'" :value="'大专'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作单位" prop="workOrg">
          <el-input
            v-model="mediatorModel.workOrg"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="参加工作时间" prop="workTime">
          <el-input
            v-model="mediatorModel.workTime"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="擅长领域" prop="field">
          <el-input
            v-model="mediatorModel.field"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="mediatorModel.email"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="mediatorModel.type">
            <el-option label="签约调解员" value="1"></el-option>
            <el-option label="社会调解员" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属调解组织">
          <el-select v-model="mediatorModel.orgId">
            <el-option
              :value="item.organizationId"
              :key="item.organizationId"
              :label="item.affiliationName + ' ' + item.branchName"
              v-for="item in orgConfig.orgs"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>

  <el-drawer v-model="table" title="调解员详细信息" direction="rtl" size="50%">
    <el-descriptions :column="1" border :data="selectedMediator">
      <el-descriptions-item label="姓名">{{
        selectedMediator?.name
      }}</el-descriptions-item>
      <el-descriptions-item label="性别">
        <template #default>
          {{
            gender.find((g) => g.value === selectedMediator?.gender)?.label ||
            "未知"
          }}
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="学历">{{
        selectedMediator?.education
      }}</el-descriptions-item>
      <el-descriptions-item label="出生日期">{{
        selectedMediator?.birthDate
      }}</el-descriptions-item>
      <el-descriptions-item label="工作单位">{{
        selectedMediator?.workOrg
      }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{
        selectedMediator?.phone
      }}</el-descriptions-item>
      <el-descriptions-item label="身份证号">{{
        selectedMediator?.idNum
      }}</el-descriptions-item>
      <el-descriptions-item label="擅长领域">{{
        selectedMediator?.field
      }}</el-descriptions-item>
      <el-descriptions-item label="参加工作时间">{{
        selectedMediator?.workTime
      }}</el-descriptions-item>
      <el-descriptions-item label="邮箱">{{
        selectedMediator?.email
      }}</el-descriptions-item>
      <el-descriptions-item label="类型">
        <template #default>
          {{
            typeOptions.find((t) => t.value === selectedMediator?.type)
              ?.label || "未知"
          }}
        </template>
      </el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
